package com.kcht.itsed.mws.extendmodel.jpa;

import com.kcht.itsed.mws.IMwsXmlObjFactory;
import com.kcht.itsed.mws.MwsXmlObjFactory;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedTypes({Object.class})
@MappedJdbcTypes(JdbcType.VARCHAR)
public class SpecEntityConverter extends BaseTypeHandler<Object> {

	private Class<Object> type;

	public SpecEntityConverter(Class<Object> type) {
		if (type == null) {
			throw new NullPointerException("Type argument cannot be null");
		}
		this.type = type;
	}

	@Override
	public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
		super.setParameter(ps, i, parameter, jdbcType);
	}

	@Override
	public Object getResult(ResultSet rs, String columnName) throws SQLException {
		return convertToEntityAttribute(rs.getString(columnName));
	}

	@Override
	public Object getResult(ResultSet rs, int columnIndex) throws SQLException {
		return convertToEntityAttribute(rs.getString(columnIndex));
	}

	@Override
	public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {
		return convertToEntityAttribute(cs.getString(columnIndex));
	}



	/**
	 *
	 * 当为Null时
	 * */
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
		ps.setString(i, convertToDatabaseColumn(parameter));
	}

	@Override
	public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return convertToEntityAttribute(rs.getString(columnName));
	}


	@Override
	public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return convertToEntityAttribute(rs.getString(columnIndex));
	}

	@Override
	public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return convertToEntityAttribute(cs.getString(columnIndex));
	}

	public String convertToDatabaseColumn(Object attribute) {
		IMwsXmlObjFactory<Object> f = MwsXmlObjFactory.create(type);
		return f.toXml(attribute);
	}

	public Object convertToEntityAttribute(String dbData) {
		IMwsXmlObjFactory<Object> f = MwsXmlObjFactory.create(type);
		return f.toModel(dbData);
	}
}
